/*
 to compress...
 d:
 cd TalkTalk\piecesofuk\Javascript
 java -jar D:\Programming\Javascript\yuicompressor-2.3.5\build\yuicompressor-2.3.5.jar jewelTube.js -o jewelTube.min.js
*/

// short URL to jewelTube.html ... http://bit.ly/jewelTube
/* TODO

  DONE: put language selection in control bar
  DONE: add 20sec skip points when lyrics data file not found
  Tidy up the code!!!!!

*/
if (typeof PIECESOFUK == "undefined") {
	var PIECESOFUK = {};
}


var ytplayer = null;
var timeoutId = null;

/* youtube api playlist format...

  http://gdata.youtube.com/feeds/api/playlists/2E98E6418C36DF54?v=2&alt=json-in-script&format=5&callback=showMyVideos

*/

PIECESOFUK.jewelTubePtr = null;

PIECESOFUK.initJewelTube = function() {
	$("body").show();
	$(".aDialog, .aControl").hide();

	if (PIECESOFUK.jewelTubePtr == null) PIECESOFUK.jewelTubePtr = new PIECESOFUK.youTube();
//	PIECESOFUK.jewelTubePtr.display();
}

PIECESOFUK.youTube = function() {
	if ($("#youTube").length) {
//		delete this;
//		return; // already exists!
	}
	var youTube = this;

	this.started = false;
//	this.id = null;
  this.lyricDataLoaded = false;
	this.skipPointsDisplayed = false;

  this.duration = 0;
  this.durationSeconds = 0;
  this.durationMinutes = 0;
  this.current = 0;
  this.dev_key = "AI39si5ZGB1rIF7dhn6_iSVb4cODOTLb1mNXMZh4w9SkHBfRvgquafK9yvbRIchpmQLMb37fQBU4EZMm1SkjvysIKKDcNtIPcw"
  this.params = { allowScriptAccess: "always" };
  this.atts = { id: "myytplayer" };

//  PIECESOFUK.infoViewPtr.update(425, 384, "youTube player", this);
//  PIECESOFUK.infoViewPtr.update(372, 400, "youTube player", this);

//  PIECESOFUK.infoViewPtr.update(372, 415, "youTube player", this);

//	$("#youTube").dialog({width: 372, height: 415, title: "jewelTube", close: this.close, focus: this.focus,
	$("#youTube").dialog({width: 372, height: 415, title: "jewelTube", focus: this.focus,
											 position: "right", beforeclose: function() {return false;}})
//  $("#infoView").html("<div id='youTube' />").css("width", "372px");
	$("#ui-dialog-title-youTube")
			   .prepend('<img class="infoViewTitleImg" src="Graphics/youtube.gif" width="16" height="16" alt="icon">')
         .parent()
				 .css("paddingLeft", "3px");


//  this.siteLanguage = this.language = google.language.Languages[$("#jq-translate-ui").val().toUpperCase()];
	this.siteLanguage = "en"; // need to allow global language change
	this.language = "en";
	this.changingLanguage = false;



/*
  var savePadding = $("#ui-dialog-title-infoViewContainer").parent().css("paddingLeft");
  $("#ui-dialog-title-infoViewContainer").prepend('<img class="infoViewTitleImg" src="Images/youtube.gif" width="16" height="16" alt="icon">')
       .parent().css("paddingLeft", "3px"); // need to remove this padding when changing views!!!!

*/

	this.loadPlaylist = function(json) { // get videos from my playlist
		if (json == undefined) {
			// handle error
		} else {
			for (var i = 0; i < json.feed.entry.length; ++i) {
				var id = json.feed.entry[i].media$group.media$thumbnail[0].url.match(/http:\/\/i.ytimg.com\/vi\/(.*)\/2.jpg/)[1];
//        $("<img>").attr("src", json.feed.entry[i].media$group.media$thumbnail[0].url).attr("id", id)
        $("<img>").attr("src", json.feed.entry[i].media$group.media$thumbnail[0].url).attr("id", "YT" + id)
				.attr("title", json.feed.entry[i].title.$t)
				.appendTo("#youTubeThumbs");
			}
		}
    $("#youTubeThumbs img").click( function() {
//      youTube.controller( $(this).attr("id"), $(this).attr("class"));
			clearTimeout(timeoutId);
			youTube.skipPointsDisplayed = false;
//      youTube.controller( $(this).attr("id"));
      youTube.controller( $(this).attr("id").slice(2));
			timeoutId = setTimeout(PIECESOFUK.jewelTubePtr.updateStatus, 1000);
    });
	}

/*
  this.close = function() {
    clearTimeout(timeoutId);
		if (ytplayer) {
//			ytplayer.stopVideo()
			delete ytplayer;
			ytplayer = null;
		}
    $("#ui-dialog-title-infoViewContainer").parent().css("paddingLeft", savePadding);
		$("#infoView").css("backgroundColor", "black");
		$("#youTube, #youTubeThumbs").remove();
		delete youTube;
		PIECESOFUK.jewelTubePtr = null;
  }
*/

/*
	this.changeLanguage = function() {
		$("#ytTranslation").unbind("click").html("");
		youTube.changingLanguage = true;
		youTube.language = null;
     $.translate().ui('select', 'option').change(function(){
      youTube.selectedLanguage = $(this).val();
      youTube.language = google.language.Languages[$(this).val().toUpperCase()];
			youTube.changingLanguage = false;
    }).val(youTube.selectedLanguage).appendTo("#ytTranslation");
    setTimeout(function() { // delay before rebind otherwise gets confused
			$("#ytTranslation").click( youTube.changeLanguage);
		}, 5000);
	}
*/

  this.controller = function(id, displayType) {
// two options: basic video; video with lyrics + skip points
// displayType = "basic", "enhanced"
    if (displayType == "basic") { this.width = 425; this.height = 356; }
    else { this.width = 320; this.height = 240; }
		youTube.id = id;

    $.ajax({
      type: "GET",
			async: false,
      url: "Data/youTube/" + youTube.id + ".js",
      dataType: "script",
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				youTube.lyricDataLoaded = false;
			},
			success: function (data, textStatus) {
				youTube.lyricDataLoaded = true;
				$("#YT" + youTube.id).addClass("withLyrics");
			}
    });

		if (youTube.started) { // if a video is already playing
		  youTube.started = false;
			ytplayer.loadVideoById(youTube.id, 0)
		} else {
      $("#youTube").html('<div id="ytapiplayer"/><div id="ytControls"><div id="ytMain">' +
        '<div id="playPauseVideo" class="playVideo"/>' +
        '<div id="ytSkipButton" class="ytButton">Skip</div>' +
        '<div id="ytLyricsButton" class="ytButton">Lyrics</div>' +
        '<div id="ytTranslationButton" class="ytButton">Translation</div>' +
				'<div id="ytVolumeButton" class="ytButton">Volume</div>' +
				'<div id="ytStatus"/>' +
				'<div id="ytVolumeContainer"><div id="ytVolumeControl"/><div id="ytVolume"/></div>' +
        '<div id="ytSkipContainer"><div id="HSkipTopText"/>' +
        '<div id="Hloaded"><div id="Hplayed"/></div>' +
        '<div id="HskipPoints"/><div id="HSkipBotText"/></div>' +
        '<div id="ytLyrics"/><div id="ytTranslation"/></div></div>');

		  this.HskipWidth = $("#ytSkipContainer").width();
      $("#playPauseVideo").unbind("click");
      $("#playPauseVideo").click( function() {
        youTube.playVideo();
      });

      $("#skipVideo").click( function() {
        ytplayer.seekTo(youTube.current + 10, true);
      });

			$("#ytVolumeButton").click( function() {
        if ($("#ytVolumeContainer").css("display") == "none") {
          $("#ytVolumeContainer").slideDown('fast');
        } else {
          $("#ytVolumeContainer").slideUp('fast');
        }
			});

      $("#theVolume").change( function() {
        var oldVolume = ytplayer.getVolume();
        var newVolume = $("#theVolume").attr("value");
        if (newVolume < 0 || newVolume > 100) {
          newVolume = oldVolume;
          $("#theVolume").attr("value", newVolume);
        }
        ytplayer.setVolume(newVolume);
      });

      $("#ytSkipButton").click( function() {
        if ($("#ytSkipContainer").css("display") == "none") {
          $("#ytSkipContainer").slideDown('fast');
        } else {
          $("#ytSkipContainer").slideUp('fast');
        }
      });
      $("#ytLyricsButton").click( function() {
        if ($("#ytLyrics").css("display") == "none") {
          $("#ytLyrics").slideDown('fast');
        } else {
          $("#ytLyrics").slideUp('fast');
        }
      });
      $("#ytTranslationButton").click( function() {
        if ($("#ytTranslation").css("display") == "none") {
          $("#ytTranslation").slideDown('fast');
					if ( $("#langSelection").html() == "" ) {
            $.translate().ui('select', 'option').change(function(){
              youTube.selectedLanguage = $(this).val();
              youTube.language = google.language.Languages[$(this).val().toUpperCase()];
			        youTube.changingLanguage = false;
            }).val(youTube.selectedLanguage).appendTo("#langSelection");
					}
					$("#langControl").show();
        } else {
          $("#ytTranslation").slideUp('fast');
					$("#langControl").hide();
        }
      });

		  this.selectedLanguage = "English";
//		  $("#ytTranslation").click( youTube.changeLanguage);

      swfobject.embedSWF("http://gdata.youtube.com/apiplayer?key=" + youTube.dev_key + "&enablejsapi=1&playerapiid=ytplayer",
                       "ytapiplayer", "372", "298", "8", null, null, youTube.params, youTube.atts);
//                       "ytapiplayer", "425", "356", "8", null, null, youTube.params, youTube.atts);
//                       "ytapiplayer", "320", "240", "8", null, null, youTube.params, youTube.atts);
//    ytplayer.loadVideoById('6yy8Bqaytio', 0)

		}


  } // end youTube.controller



	this.id = null;
  $("#youTube").html($("#youTubeDescriptionHTML").html());
  $("#jewelTubeVideos").html("<div id='youTubeThumbs' />");
	// a maximum of 50 videos can be retrieved from a playlist
//  $.getJSON("http://gdata.youtube.com/feeds/api/playlists/2E98E6418C36DF54?v=2&alt=json-in-script&format=5&callback=?",
  $.getJSON("http://gdata.youtube.com/feeds/api/playlists/2E98E6418C36DF54?v=2&max-results=50&alt=json-in-script&format=5&callback=?",
						this.loadPlaylist);


  this.playVideo = function() {
    $("#playPauseVideo").removeClass("playVideo").addClass("pauseVideo");
    ytplayer.playVideo();
    $("#playPauseVideo").unbind("click");
    $("#playPauseVideo").click( function() {
      youTube.pauseVideo();
    });
  }

  this.pauseVideo = function() {
    $("#playPauseVideo").removeClass("pauseVideo").addClass("playVideo");
    ytplayer.pauseVideo();
    $("#playPauseVideo").unbind("click");
    $("#playPauseVideo").click( function() {
      youTube.playVideo();
    });
  }

	this.displaySkipPoints = function() {
    youTube.skipPointsDisplayed = true;
		youTube.started = true;
    youTube.duration = ytplayer.getDuration();
    youTube.duration = Math.floor(youTube.duration)
    youTube.durationSeconds = youTube.duration % 60;
    youTube.durationMinutes = Math.floor(youTube.duration / 60);
    $("#Hloaded").css("width", "0px");
    $("#Hplayed").css("width", "0px");
		if (!youTube.lyricDataLoaded) { // no lyric data so add skip points every 20secs
      $("#HskipPoints, #HSkipTopText, #HSkipBotText").html("");
      $("#ytLyrics").html("Lyrics not available");
      $("#ytTranslation").html("Translations not available");
			var topBot = "T";
			for (var time = 0; time < youTube.duration-20; time += 20 ) {
				var leftPos = Math.floor(time/youTube.duration * youTube.HskipWidth);
			  var $img = $("<img />").attr("src", "Graphics/skipPoint.png").addClass("skipClick")
				    .css("left", leftPos + "px").data("Start", time);
			  $("#HskipPoints").append($img);
			  if (leftPos > 8) leftPos = leftPos - 8;
			  else leftPos = 0;
        var $theSpan = $("<span></span>").addClass("skipPoint").addClass("skipClick")
					     .text( Math.floor(time / 60)+":"+ ( time%60 < 10 ? "0" + time%60 : time%60))
               .css("left", leftPos + "px").data("Start", time);
        if ( topBot == "T" ) {
				  $("#HSkipTopText").append($theSpan);
				  topBot = "B";
			  } else {
				  $("#HSkipBotText").append($theSpan);
				  topBot = "T";
			  }
			}
		} else {
		  var topBot = "T"; // for horizontal skip
		  $("#HskipPoints, #HSkipTopText, #HSkipBotText, #ytLyrics, #ytTranslation").html("");
      for (var i = 0; i < PIECESOFUK.verses.length; i++) {
			  var leftPos = Math.floor(PIECESOFUK.verses[i].Start/youTube.duration * youTube.HskipWidth);
			  var $img = $("<img />").attr("src", "Graphics/skipPoint.png").addClass("skipClick")
				    .css("left", leftPos + "px").data("Start", PIECESOFUK.verses[i].Start);
			  $("#HskipPoints").append($img);
			  if (leftPos > 14) leftPos = leftPos - 14;
			  else leftPos = 0;
        var $theSpan = $("<span></span>").addClass("skipPoint").addClass("skipClick")
					     .text(PIECESOFUK.verses[i].Type)
               .css("left", leftPos + "px").data("Start", PIECESOFUK.verses[i].Start);
        if ( topBot == "T" ) {
				  $("#HSkipTopText").append($theSpan);
				  topBot = "B";
			  } else {
				  $("#HSkipBotText").append($theSpan);
				  topBot = "T";
			  }
      }
		}
    $(".skipClick").click( function() {
      var seekTo = $(this).data("Start");
      ytplayer.seekTo(seekTo, true);
			if (youTube.lyricDataLoaded) {
        for (var i = 0; i < PIECESOFUK.lyrics.length; i++) {
          if (PIECESOFUK.lyrics[i].Start >= seekTo) {
            $("#ytLyrics").html("");
            PIECESOFUK.lyricPointer = i;
            PIECESOFUK.nextLyricTime = PIECESOFUK.lyrics[PIECESOFUK.lyricPointer].Start;
            break;
          }
        }
			}
    });
	} // end youTube.displaySkipPoints

  this.ytplayerStateChange = function(newState) {
    if (newState == -1) {
		  $("#ytStatus").text("unstarted");
			ytplayer.loadVideoById(youTube.id, 0); // autostarts
		}
    if (newState == 0) $("#ytStatus").text("ended");
    if (newState == 1) {
			if (!youTube.skipPointsDisplayed) youTube.displaySkipPoints();
      if ( $(".playVideo").length) {
        $("#playPauseVideo").removeClass("playVideo").addClass("pauseVideo");
        $("#playPauseVideo").unbind("click");
        $("#playPauseVideo").click( function() {
          youTube.pauseVideo();
        });
      }
      $("#ytStatus").text("playing");

			if (!youTube.started) {
				timeoutId = setTimeout(PIECESOFUK.jewelTubePtr.updateStatus, 100);
			}
    }
    if (newState == 2) $("#ytStatus").text("paused");
    if (newState == 3) $("#ytStatus").text("buffering");
    if (newState == 5) {
      $("#ytStatus").text("video cued");
    }
  }

  this.ytplayerError = function(errorCode) {
    if (errorCode == 100) alert("video not found or has been removed");
  }

  this.updateStatus = function() {
		if (ytplayer == null) return;
		if (typeof(ytplayer.getCurrentTime) != "function") return;
    youTube.current = ytplayer.getCurrentTime();
    $("#time").text(Math.floor(youTube.current / 60) +
        ":" + Math.floor(youTube.current) % 60 + "/" +
        youTube.durationMinutes + ":" + youTube.durationSeconds);
    if (ytplayer.getVideoBytesTotal() > 0) {
      var HpcLoaded = Math.floor( ytplayer.getVideoBytesLoaded()/ytplayer.getVideoBytesTotal() * youTube.HskipWidth);
      $("#Hloaded").css("width", HpcLoaded + "px");
    }
    if (youTube.duration > 0) {
      var Hplayed = Math.floor ( youTube.current/youTube.duration * youTube.HskipWidth);
      $("#Hplayed").css("width", Hplayed + "px");
    }
		if (youTube.lyricDataLoaded) {
      if (youTube.current > PIECESOFUK.nextLyricTime) {
        $("#ytLyrics").html(PIECESOFUK.lyrics[PIECESOFUK.lyricPointer].Line);
/* remove until global language is re-implemented
			if (youTube.siteLanguage != google.language.Languages[$("#jq-translate-ui").val().toUpperCase()]) {
				youTube.language = youTube.siteLanguage = google.language.Languages[$("#jq-translate-ui").val().toUpperCase()];
			}
*/
//			if (youTube.language) {
			  if (youTube.language != "en") {
				  google.language.translate(PIECESOFUK.lyrics[PIECESOFUK.lyricPointer].Line, "en",
																youTube.language, function(result) {
            if (!result.error) {

              $("#ytTranslation").html(result.translation)
            }
          });
			  }
			  else $("#ytTranslation").html("Select the translation language");
			/*
			else if (!youTube.changingLanguage){
				$("#ytTranslation").html("Click to include translated lyrics or to change language");
			}
			*/
/*
      if ( $("#jq-translate-ui").val() != "English") {
        google.language.translate(youTube.lyrics[youTube.lyricPointer].Line, "en",
            google.language.Languages[$("#jq-translate-ui").val().toUpperCase()], function(result) {
          if (!result.error) {
            $("#ytTranslation").html(result.translation)
          }
        });
      }
*/
        ++PIECESOFUK.lyricPointer;
        PIECESOFUK.nextLyricTime = PIECESOFUK.lyrics[PIECESOFUK.lyricPointer].Start;
      }
		}
/*
    if (current > nextVideoInfoTime) {
      $("#videoInfoLeft").html(videoInfo[videoInfoPointer].Html);
      ++videoInfoPointer;
      nextVideoInfoTime = videoInfo[videoInfoPointer].Start;
    }
*/
//  intervalId = setTimeout(PIECESOFUK.infoViewFn.updateStatus, 1000);
  timeoutId = setTimeout(PIECESOFUK.jewelTubePtr.updateStatus, 1000);

  }
} // end PIECESOFUK.youTube

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener('onStateChange', 'PIECESOFUK.jewelTubePtr.ytplayerStateChange');
  ytplayer.addEventListener('onError', 'PIECESOFUK.jewelTubePtr.ytplayerError');
  timeoutId = setTimeout(PIECESOFUK.jewelTubePtr.updateStatus, 100);
	var curVolume = ytplayer.getVolume();
	$("#ytVolumeControl").slider( {
		orientation: "horizontal", min: 0, max: 100, value: curVolume,
		slide: function(event, ui) {
			$("#ytVolume").text(ui.value);
			ytplayer.setVolume(ui.value);
    }
	});
	$("#ytVolume").text(curVolume);
}
